package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVO;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVO;
import com.atguigu.gulimall.auth.vo.UserRegistVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        String code = UUID.randomUUID().toString().substring(0, 4);
        //1、接口防刷
        String check = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (check != null) {
            System.out.println(BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
        }

        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code, 60, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_PREFIX + phone, code, 30, TimeUnit.MINUTES);
        R r = thirdPartyFeignService.sendCode(phone, code);

        return R.ok();
    }

    @PostMapping("/regist")
    //将UserRegistVO的验证结果封装到BindingResult
    //RedirectAttributes 模拟重定向携带数据
    //重定向携带数据，利用session原理，将数据放在session中，只要跳到下一个页面取出这个数据以后，session里面的数据就会删掉（这样会有分布式下的session问题）
    public String regist(@Valid UserRegistVO vo, BindingResult result, RedirectAttributes redirectAttributes) {
        //校验出错
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //校验验证码
        String code = vo.getCode();
        String check = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + vo.getPhone());
        if (StringUtils.isEmpty(check) || !check.equals(code)) {
            Map<String, Object> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            //验证码出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //验证码同通过，删除redis的验证码
        redisTemplate.delete(AuthServerConstant.SMS_CODE_PREFIX + vo.getPhone());
        R regist = memberFeignService.regist(vo);
        if (regist.getCode() == 0) {
            //成功
            return "redirect:/login.html";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", regist.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            //验证码出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVO vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登录
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            MemberRespVO respVO = login.getData("data", new TypeReference<MemberRespVO>() {});
            System.out.println("成功登录 --- "+respVO);
            //存入session
            session.setAttribute(AuthServerConstant.LOGIN_USER,respVO);
            return "redirect:http://gulimall.com";
        } else {
            HashMap<String, Object> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

//    @GetMapping("/login.html")
//    public String loginPage(HttpSession session){
//        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
//        if (attribute == null) {
//            //没有登录
//            return "login";
//        }
//        return "redirect:http://gulimall.com";
//
//    }
}
